<?php

namespace app\admin\controller;

use app\admin\model\SystemAdmin;
use app\admin\model\SystemQuick;
use app\common\controller\AdminController;
use app\Request;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use app\admin\model\AppConfig as AppConfigModel;
use app\admin\model\MallGoods as MallGoodsModel;
use app\admin\model\MallCate as MallCateModel;
use app\admin\model\MallDealLog as MallDealLogModel;
use app\admin\model\Order as OrderModel;
use app\admin\model\Shop as ShopModel;

class Index extends AdminController
{

    /**
     * 后台主页
     * @param Request $request
     * @return string
     */
    public function index(Request $request): string
    {
        $appid=$request->adminUserInfo['appid'];
        if(!$appid){//没有appid去选择应用
            $admin_id=$request->adminUserInfo['id'];
            $data=AppConfigModel::where('admin_id',$admin_id)->select();
            return $this->fetch('/index/app_list', ['data' => $data]);
        }
        $app_info=AppConfigModel::where('appid',$appid)->find();
        return $this->fetch('', ['admin' => $request->adminUserInfo,'app_name'=> $app_info['app_name']??'']);
    }

    /**
     * 应用列表页
     * @param Request $request
     * @return string
     */
    public function appList(Request $request): string
    {
        $admin_id=$request->adminUserInfo['id'];
        $data=AppConfigModel::where('admin_id',$admin_id)->select();
     
        return $this->fetch('', ['data' => $data,'username' => $request->adminUserInfo['username']]);
    }
    
    /**
     * 应用配置
     * @param Request $request
     * @return string
     */
    public function appListSet(Request $request)
    {
        $appid=$request->get('appid','');
        $type=$request->get('type',2);
        if($type==1){//跳转首页
            $data=$request->adminUserInfo;
            $data['appid']=$appid;
            session('admin',$data);
            SystemAdmin::where('id',$request->adminUserInfo['id'])->update(['now_appid'=>$appid]);
            // return  redirect('/admin#/admin/appinfo.app_interface_config/indexs');
            return  redirect('index/welcome');
        }elseif($type==2){//跳转新增应用页
            $data=$request->adminUserInfo;
            $data['appid']='';
            session('admin',$data);
            SystemAdmin::where('id',$request->adminUserInfo['id'])->update(['now_appid'=>$appid]);
            return  redirect('/admin/appinfo.app_config/indexs');
        }
    }

    /**
     * 后台欢迎页
     * @return string
     * @throws Exception
     */
    public function welcome(Request $request): string
    {
        $tpVersion    = \think\facade\App::version();
        $mysqlVersion = Db::query("select version() as version")[0]['version'] ?? '未知';
        $phpVersion   = phpversion();
        $versions     = compact('tpVersion', 'mysqlVersion', 'phpVersion');
        $quick_list   = SystemQuick::field('id,title,icon,href')
            ->where(['status' => 1])->order('sort', 'desc')->limit(50)->select()->toArray();
        $quicks       = array_chunk($quick_list, 8);
        $this->assign(compact('quicks', 'versions'));

        // 数据统计
        $appid=$request->adminUserInfo['appid']??"";
        $data=$this->findData($appid,[],1);
        // 报表统计
        $appid=$request->adminUserInfo['appid']??"";
        $lineData=$this->findLine($appid,1);
               
        $this->assign('data', $data);
        $this->assign('lineData', $lineData);
        
        return $this->fetch();
    }

    public function ajaxData(Request $request){
        $appid=$request->adminUserInfo['appid']??"";
        $post = $request->post();
        $data=$this->findData($appid,$post,0);
        
        $this->success('查询成功',$data);
    }

    public function ajaxLine(Request $request){
        $appid=$request->adminUserInfo['appid']??"";
        $sel_type = $request->post('sel_type',1);
        $data=$this->findLine($appid,$sel_type,0);
        
        $this->success('查询成功',$data);
    }
    
    // 查询统计数据
    public function findData($appid,$post,$all){
       
        $where['appid']=$appid;

        // 带时间查询
        if(isset($post['time_type'])&&(!empty($post['time_type']))){
            if($post['time_type']==1)$between=[strtotime("first day of January"),strtotime("last day of December")];//年
            if($post['time_type']==2)$between=[strtotime(date('Y-m-01 00:00:00')),strtotime(date('Y-m-t 23:59:59'))];//月
            if($post['time_type']==3)$between=[strtotime(date('Y-m-d 00:00:00')),strtotime(date('Y-m-d 23:59:59'))];//日
            $where[]=['create_time','between',$between];
        }

        // 带平台类型查询
        if(isset($post['shop_type'])&&(!empty($post['shop_type']))){
            if($post['shop_type']==1) $where[]=['app_type','=' ,10];//拉
            if($post['shop_type']==2) $where[]=['app_type','=' ,20];//乐
            if($post['shop_type']==3) $where[]=['app_type','=' ,30];//随
        }
   
        if(isset($post['card_type'])&&($post['card_type']==1)||$all){
            // 订单统计笔数
            $order_complete=(new OrderModel)->where($where)->where('status','SUCCESS')->count()??0;//已完成
            $order_cancel=(new OrderModel)->where($where)->where('status','in',['PART_REFUND','REFUND'])->count()??0;//已退款
        }

        if(isset($post['card_type'])&&($post['card_type']==2)||$all){
            // 商铺统计
            $shop=(new ShopModel)->where($where)->count();//总计
            $shop_pass=(new ShopModel)->where($where)->where('status',1)->count();//审核通过
        }

        if(isset($post['card_type'])&&($post['card_type']==3)||$all){
            // 订单统计金额
            $order_complete_money=(new OrderModel)->where($where)->where('status','SUCCESS')->sum('payer_amount')??0;//已完成
            $order_cancel_money=(new OrderModel)->where($where)->where('status','in',['PART_REFUND','REFUND'])->sum('refund_amount')??0;//已退款
        }

        $data=[
            'order_complete'=>$order_complete??0,
            'order_cancel'=>$order_cancel??0,

            'shop'=>$shop??0,
            'shop_pass'=>$shop_pass??0,

            'order_complete_money'=>isset($order_complete_money)?round($order_complete_money/100,2):0,
            'order_cancel_money'=>isset($order_cancel_money)?round($order_cancel_money/100,2):0,
        ];

        return $data;
    }

    // 查询报表数据
    public function findLine($appid,$sel_type){
        $currentTime = time(); // 当前时间戳

        if($sel_type==1){//近一周   
            for ($i = 0; $i < 7; $i++) {
                $dayStart = strtotime("-$i days midnight", $currentTime); // 当天的 00:00:00
                $dayEnd = strtotime("-$i days 23:59:59", $currentTime);   // 当天的 23:59:59
            
                $timeArr[date("Y-m-d", $dayStart)]['start_time']=$dayStart;
                $timeArr[date("Y-m-d", $dayEnd)]['end_time']=$dayEnd;
            }
        }

        if($sel_type==2){//近一个月
            for ($i = 0; $i < 4; $i++) {
                $weekStart = strtotime("last Monday -" . ($i * 7) . " days", $currentTime);
                $weekEnd = strtotime("next Sunday -" . ($i * 7) . " days 23:59:59", $currentTime);
            
                $timeArr[date("m-d", $weekStart).'至'.date("m-d", $weekEnd)]['start_time']=$weekStart;
                $timeArr[date("m-d", $weekStart).'至'.date("m-d", $weekEnd)]['end_time']=$weekEnd;

            }
        }

        if($sel_type==3){//近一年
            for ($i = 0; $i < 12; $i++) {
                $monthStart = strtotime("first day of -$i months midnight", $currentTime);
                $monthEnd = strtotime("last day of -$i months 23:59:59", $currentTime);

                $timeArr[date("Y-m", $monthStart)]['start_time']=$monthStart;
                $timeArr[date("Y-m", $monthStart)]['end_time']=$monthEnd;
            }
        }

        $timeArr=array_reverse($timeArr);//倒序

        foreach($timeArr as $k=>$v){
            $where['appid']=$appid;
            $where[]=['create_time','between',[$v['start_time'],$v['end_time']]];

            $lakala_num[]=abs((new OrderModel)->where($where)->where('app_type',10)->sum('payer_amount'))/100;//拉卡拉订单
            $leshua_num[]=abs((new OrderModel)->where($where)->where('app_type',20)->sum('payer_amount'))/100;//乐刷订单
            $suixinfu_num[]=abs((new OrderModel)->where($where)->where('app_type',30)->sum('payer_amount'))/100;//随心付订单
            $totel_num[]=abs((new OrderModel)->where($where)->where('app_type','in',[10,20,30])->sum('payer_amount'))/100;//全部订单
            $key_name[]=$k;
            
            $where=[];
        }

        $data=[
          'lakala_num'=>$lakala_num,
          'leshua_num'=>$leshua_num,
          'suixinfu_num'=>$suixinfu_num,
          'totel_num'=>$totel_num,
          'key_name'=>$key_name,
        ];

        return $data;
    }

    /**
     * 修改管理员信息
     * @param Request $request
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function editAdmin(Request $request): string
    {
        $id  = $this->adminUid;
        $row = (new SystemAdmin())
            ->withoutField('password')
            ->find($id);
        empty($row) && $this->error('用户信息不存在');
        if ($request->isPost()) {
            $post = $request->post();
            $this->isDemo && $this->error('演示环境下不允许修改');
            $rule = [];
            $this->validate($post, $rule);
            try {
                $login_type = $post['login_type'] ?? 1;
                if ($login_type == 2) {
                    $ga_secret = (new SystemAdmin())->where('id', $id)->value('ga_secret');
                    if (empty($ga_secret)) $this->error('请先绑定谷歌验证器');
                }
                $save = $row->allowField(['head_img', 'phone', 'remark', 'update_time', 'login_type'])->save($post);
            }catch (\PDOException $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        $notes = (new SystemAdmin())->notes;
        $this->assign('notes', $notes);
        return $this->fetch();
    }

    /**
     * 修改密码
     * @param Request $request
     * @return string
     */
    public function editPassword(Request $request): string
    {
        $id  = $this->adminUid;
        $row = (new SystemAdmin())
            ->withoutField('password')
            ->find($id);
        if (!$row) {
            $this->error('用户信息不存在');
        }
        if ($request->isPost()) {
            $post = $request->post();
            $this->isDemo && $this->error('演示环境下不允许修改');
            $rule = [
                'password|登录密码'       => 'require',
                'password_again|确认密码' => 'require',
            ];
            $this->validate($post, $rule);
            if ($post['password'] != $post['password_again']) {
                $this->error('两次密码输入不一致');
            }

            try {
                $save = $row->save([
                    'password' => password($post['password']),
                ]);
            }catch (Exception $e) {
                $this->error('保存失败');
            }
            if ($save) {
                $this->success('保存成功');
            }else {
                $this->error('保存失败');
            }
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * 设置谷歌验证码
     * @param Request $request
     * @return string
     * @throws Exception
     */
    public function set2fa(Request $request): string
    {
        $id  = $this->adminUid;
        $row = (new SystemAdmin())->withoutField('password')->find($id);
        if (!$row) $this->error('用户信息不存在');
        // You can see: https://gitee.com/wolf-code/authenticator
        $ga = new \Wolfcode\Authenticator\google\PHPGangstaGoogleAuthenticator();
        if (!$request->isAjax()) {
            $old_secret = $row->ga_secret;
            $secret     = $ga->createSecret(32);
            $ga_title   = $this->isDemo ? 'EasyAdmin8演示环境' : '可自定义修改显示标题';
            $dataUri    = $ga->getQRCode($ga_title, $secret);
            $this->assign(compact('row', 'dataUri', 'old_secret', 'secret'));
            return $this->fetch();
        }
        $this->isDemo && $this->error('演示环境下不允许修改');
        $post      = $request->post();
        $ga_secret = $post['ga_secret'] ?? '';
        $ga_code   = $post['ga_code'] ?? '';
        if (empty($ga_code)) $this->error('请输入验证码');
        if (!$ga->verifyCode($ga_secret, $ga_code)) $this->error('验证码错误');
        $row->ga_secret  = $ga_secret;
        $row->login_type = 2;
        $row->save();
        $this->success('操作成功');
    }
    

}
